<template>
  <div class="express_details">
    <el-container class="base_details_container">
      <BackTitleView :title="title" />
      <el-main>
        <div class="base_details_content">
          <div class="content">
            <div class="base_details_title">基本信息</div>
            <div class="base_details_content_second">
              <el-form ref="expressFormRef" :disabled="readOnly" :model="expressForm" :rules="expressRules"
                label-width="100px" class="base_details_form">
                <el-form-item label="模版名称" prop="name">
                  <el-input v-model="expressForm.name" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="全国价格" prop="money">
                  <el-input-number v-model.number="expressForm.money" :min="0" :precision="2" :disabled="readOnly" :controls="false" controls-position="right"/>
                </el-form-item>
              </el-form>
            </div>
            <div class="base_details_title">特殊区域价格设置</div>
            <div class="base_details_content_second">
              <DynamicParams ref="dynamicParams" :template="template" :data="data" :operation=$.DPOperation(readOnly)
                :showDefault="false" addText="添加">
                <el-table-column label="区域范围" align="center">
                  <template #default="scope">
                    <div class="table_tag_box">
                      <el-tag v-for="(tag, index) in scope.row.areaItemList" :key="index" size="large"
                        :closable="!readOnly" :disable-transitions="false" @close="delArea(index, scope.$index)">
                        {{ tag.areaName }}
                      </el-tag>
                      <el-button @click="addArea(scope.$index)" size="default" v-if="!readOnly">添加区域</el-button>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="首件" align="center" width="130">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.priceNum" :min="1" :disabled="readOnly" controls-position="right" />
                  </template>
                </el-table-column>
                <el-table-column label="首费(¥)" align="center" width="130">
                  <template #default="scope">
                    <el-input v-model.number="scope.row.price" placeholder="请输入" :disabled="readOnly" />
                  </template>
                </el-table-column>
                <el-table-column label="续件" align="center" width="130">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.addPriceNum" :min="1" :disabled="readOnly" controls-position="right" />
                  </template>
                </el-table-column>

                <el-table-column label="续费(¥)" align="center" width="130">
                  <template #default="scope">
                    <el-input v-model.number="scope.row.addPrice" placeholder="请输入" :disabled="readOnly" />
                  </template>
                </el-table-column>
              </DynamicParams>
            </div>
          </div>
        </div>
      </el-main>
      <el-footer>
        <el-button @click="back">取消</el-button>
        <el-button @click="save" type="primary" v-if="!readOnly">保存</el-button>
      </el-footer>
    </el-container>
    <el-dialog v-model="dialogVisible" title="添加区域" width="35%" top="35vh" class="base_dialog">
      <el-form ref="areaFormRef" :model="areaForm" :rules="areaRules" label-width="100px">
        <el-form-item label="省份选择" prop="value">
          <el-select v-model="areaForm.value" placeholder="请选择">
            <el-option v-for="(item, index) in provinceData" :key="index" :label="item.areaName" :value="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitAreaForm">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BackTitleView from "@com/BackTitleView.vue";
import DynamicParams from "@com/DynamicParams.vue";
import { ref, reactive } from "vue";
import useRoute from "@util/router";
import $ from "@util/base"
import { $msg } from "@ui/msg"
import api from "@api/express"
// import provinceData from "@/assets/province"
const route = useRoute()

const urlQuery = route.query()
var readOnly = false
var title = "邮费模板详情"
$.handleCRU(urlQuery.type, {
  show: () => {
    readOnly = true
    title = "邮费模板详情"
    getData()
  },
  add: () => {
    title = "新增邮费模板"
  },
  modify: () => {
    title = "修改邮费模板"
    getData()
  }
})

const provinceData = ref([])

chooseArea()
function chooseArea() {
  api.chooseArea(val => {
    provinceData.value = val
  })
}

function getData() {
  api.details(route.query().code, val => {
    expressForm.name = val.name
    expressForm.money = val.money
    data.value = val.itemList
  })
}

const expressFormRef = ref(null)

const expressForm = reactive({
  name: '',
  money: ''
})

const expressRules = {
  name: [{
    required: true,
    message: '请输入模板名称',
    trigger: 'blur',
  }],
  money: [{
    required: true,
    message: '请输入全国价格',
    trigger: 'blur',
  }],
}

const template = {
  areaItemList: [],
  price: null,
  priceNum: 1,
  addPriceNum: 1,
  addPrice: null
}

const data = ref([
//   {
//   areaItemList: [
//     // {
//     // areaCode: null,
//     // areaName: null
//     // }
//   ],
//   price: null,
//   priceNum: 1,
//   addPriceNum: 1,
//   addPrice: null
// }
])

const dynamicParams = ref(null)
const dialogVisible = ref(false)
const areaFormRef = ref('')
const areaForm = reactive({
  value: ''
})
const areaRules = {
  value: [{
    required: true,
    message: '请选择省份',
    trigger: 'change',
  }],
}

function addArea(index) {
  areaIndex.value = index
  dialogVisible.value = true
}

const areaIndex = ref(0)

function submitAreaForm() {
  areaFormRef.value.validate((valid) => {
    if (valid) {
      let areaValue = provinceData.value[areaForm.value]
      let nowValue = (dynamicParams.value.getValue())[areaIndex.value]
      nowValue.areaItemList.push(areaValue)
      dynamicParams.value.modifyData(areaIndex.value, nowValue)
      dialogVisible.value = false
    }
  })
}

const delArea = (tag, index) => {
  let nowValue = (dynamicParams.value.getValue())[index]
  nowValue.areaItemList.splice(tag, 1)
  dynamicParams.value.modifyData(index, nowValue)
}

function save() {
  expressFormRef.value.validate((valid) => {
    if (valid) {
      let value = dynamicParams.value.getValue()
      value = value.remove((e) => {
        return $.isEmpty(e.areaItemList) 
        && $.isEmpty(e.price)
        && $.isEmpty(e.addPrice)
      })
      if (checkArea(value)) {
        $.handleCRU(route.query().type, {
          add: () => { addData(value) },
          modify: () => { modifyData(value) }
        })
      }
    }
  })
}

function addData(value) {
  api.add(expressForm, value, () => {
    $msg.succ("添加成功")
    back()
  })
}
function modifyData(value) {
  console.log(value)
  api.update(route.query().code, expressForm, value, () => {
    $msg.succ("修改成功")
    back()
  })
}
function checkArea(value) {
  if (value.length <= 0) {
    // $msg.error("请添加区域价格")
    return true
  }
  let areaCodeList = []
  for (let i = 0; i < value.length; i++) {
    if ($.isEmpty(value[i].areaItemList)) {
      $msg.error("请添加区域")
      return false
    } else {
      value[i].areaItemList.map(val => areaCodeList.push(val.areaCode))
    }
    if ($.isEmpty(value[i].priceNum)) {
      $msg.error("请填写首件")
      return false
    }
    if ($.isEmpty(value[i].price)) {
      $msg.error("请填写首费")
      return false
    }
    if ($.isEmpty(value[i].addPriceNum)) {
      $msg.error("请填写续件")
      return false
    }
    if ($.isEmpty(value[i].addPrice)) {
      $msg.error("请填写续费")
      return false
    }
  }
  let setList = new Set(areaCodeList)
  if (areaCodeList.length != setList.size) {
    $msg.error("区域范围设置重复")
    return false
  }
  return true
}

function back() {
  route.go(-1)
}

</script>

<style lang="scss">
.express_details {
  height: 100%;
  
  .table_tag_box {
    text-align: left;

    .el-tag {
      margin-right: 10px;
    }
  }
}
</style>